//
//  TLShortStoryViewController.m
//  WXReader
//
//  Created by huaya on 2025/1/14.
//  Copyright © 2025 Andrew. All rights reserved.
//

#import "TLShortStoryViewController.h"
#import "TLMallListTableViewCell.h"

#import "TLShortStoryHeadTableViewCell.h"
#import "TLShortStoryContentTableViewCell.h"
#import "TLShortStoryLockTableViewCell.h"
#import "TLShortStoryScrollTableViewCell.h"
#import "TLBookListForSSModel.h"

#import "TLRechargeViewController.h"
#import "TLRechargeCoinsViewController.h"
#import "TLAlterView.h"
#import "TLShortStoryCommentTableViewCell.h"

#import "TL_CommentsViewController.h"
#import "TLUnlockSSVipView.h"
typedef NS_ENUM(NSInteger, UIShortStoryCellType) {
    UIShortStoryCellTypeHeader = 0,
    UIShortStoryCellTypeContent,
    UIShortStoryCellTypeVip,
    UIShortStoryCellTypeComment,
    UIShortStoryCellTypeLock,
    UIShortStoryCellTypeNextHeader,
};

typedef NS_ENUM(NSInteger, DJReaderBVButtonType) {
    DJReaderBVButtonType_save   = 0,
    DJReaderBVButtonType_comment,
    DJReaderBVButtonType_dayNight,
    DJReaderBVButtonType_previous,
    DJReaderBVButtonType_next,
};

@interface TLShortStoryViewController ()<UITableViewDelegate,UITableViewDataSource,MKReaderNavigationViewDelegate,MKReaderSettingDelegate>

@property (nonatomic, strong) UIView *navView;
@property (nonatomic, strong) UILabel *navTitleLab;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, assign) int scrollStatus;
@property (nonatomic, strong) UIButton *backBtn;
@property (nonatomic, strong) TLBookListForSSModel *dataModel;
@property (nonatomic, strong) NSMutableArray *tableArr;

@property (nonatomic, strong) NSCache *htmlCache; // 在类初始化中创建
@property (nonatomic, assign) BOOL isLoading;

@property (nonatomic, strong) NSDate *startDate;
@property (nonatomic, strong) NSMutableArray *cellTypeArr;

//@property (nonatomic, strong) MKReaderNavigationView *navigationView;
@property (nonatomic, strong) MKReaderBottomView *bottomView;
@property (nonatomic, strong) MKReaderSettingView *settingView;

@property (nonatomic, assign) NSNumber *curChaptertId;
@property (nonatomic, assign) bool isFullScreen;

@property (nonatomic, strong) NSMutableArray * historyMArray;

@property (nonatomic, strong) TLUnlockSSVipView *unlockView;

@property (nonatomic, assign) int scrollToIndex;
@property (nonatomic, assign) bool isNoScroll;
@property (nonatomic, assign) bool isSendRead;
@end

@implementation TLShortStoryViewController
- (TLUnlockSSVipView *)unlockView{
    if (!_unlockView) {
        _unlockView = [TLUnlockSSVipView createView];
        _unlockView.hidden = YES;
        MJWeakSelf
        _unlockView.closeBlock = ^{
            weakSelf.curChaptertId = @(0);
        };
        _unlockView.gotoVipBlock = ^{
            weakSelf.isNoScroll = NO;
            weakSelf.isSendRead = NO;
            TLRechargeViewController *vc = [[TLRechargeViewController alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
    }
    return _unlockView;
}
- (NSMutableArray *)historyMArray{
    if (!_historyMArray) {
        _historyMArray = [NSMutableArray new];
    }
    return _historyMArray;
}
- (NSMutableArray *)cellTypeArr{
    if (!_cellTypeArr) {
        _cellTypeArr = [NSMutableArray new];
    }
    return _cellTypeArr;
}
- (UIView *)navView{
    if (!_navView) {
        _navView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, PUB_NAVBAR_HEIGHT)];
        [_navView setBackgroundColor:[UIColor colorWithHexString:@"#F6F6F6"]];
        _backBtn = [[UIButton alloc] initWithFrame:CGRectMake(6, PUB_NAVBAR_HEIGHT - 28 - 6, 28, 28)];
        [_backBtn setImage:[UIImage imageNamed:@"tzxqy_fh"] forState:UIControlStateNormal];
        [_backBtn addTarget:self action:@selector(backAction) forControlEvents:UIControlEventTouchUpInside];
        
        [_navView addSubview:_backBtn];
         
        _navTitleLab = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(_backBtn.frame)+10, PUB_NAVBAR_HEIGHT - 28 - 6, kScreenWidth, 28)];
        _navTitleLab.text = @"";
        _navTitleLab.textColor = [UIColor colorWithWhite:0 alpha:0];
        _navTitleLab.font = [UIFont systemFontOfSize:17 weight:UIFontWeightMedium];
        _navTitleLab.textAlignment = NSTextAlignmentLeft;
        [_navView addSubview:_navTitleLab];
        
    }
    return _navView;
}
- (void)backAction{
    self.isSendRead = YES;
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    if (self.isSendRead) {
        [TL_UtilsHelper upReadingDurationWithWorksId:self.dataModel.worksId andChaptertId:self.curChaptertId andStartDate:self.startDate];
    }
    
}
- (void)viewDidLoad {
    [super viewDidLoad];
    _isNoScroll = NO;
    _isSendRead = YES;
    _startDate = [NSDate date];
    
    self.isLoading = NO;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    
    [self.view addSubview:self.navView];
    [self.navView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_offset(PUB_NAVBAR_HEIGHT);
    }];
    
    [self.view addSubview:self.tableView];
    [self.tableView reloadData];
    
//    [self.view addSubview:self.navigationView];
    [self.view addSubview:self.bottomView];
    [self.view addSubview:self.settingView];
    
//    [self.navigationView showViewWithShow:NO];
    [self.bottomView showViewWithShow:NO];
    [self.settingView showViewWithShow:NO];
    
    [self.view addSubview:self.unlockView];
    self.unlockView.frame = CGRectMake(16, kScreenHeight-88-13-MK_SCREEN_SAVE_BOTTOM_HEIGHT, kScreenWidth-16*2, 88);
    
    [self resetUI:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self networkWithWorksId:[NSNumber numberWithString:self.worksId] success:nil];
}
- (void)networkWithWorksId:(NSNumber *)worksId success:(MKVoidBlock)success delay:(int)sec{
    
    if (!worksId || worksId.intValue == 0) {
        return;
    }
    
    [self updateShowViewWithIsFull:YES];
    [self.cellTypeArr removeAllObjects];
    
    NSMutableDictionary *param = [NSMutableDictionary new];
    
    [param setObject:worksId forKey:@"worksId"];
    
//    NSNumber *isAuto = [[NSUserDefaults standardUserDefaults] objectForKey:IS_AUTO_BUY_NEXT_CHAPTER];
    
    [param setObject:@(0) forKey:@"isAutoBuy"];
    
    UIView *loadinView = [TL_TopAlertManager showLoading:self.view];
    
    
    [APIManager sendGetRequest:[APIURLManager querySSChapterByWorksId] parameters:@{@"worksId":worksId} model:nil success:^(BOOL successed, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        [loadinView removeFromSuperview];
        
        if (successed) {
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(sec * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.cellTypeArr removeAllObjects];
                
                if (self.dataModel) {
                    
                    if (!self.curChaptertId) {
                        self.curChaptertId = self.dataModel.lastReadChapterId;
                    }
                    
                    [TL_UtilsHelper upReadingDurationWithWorksId:self.dataModel.worksId andChaptertId:self.curChaptertId andStartDate:self.startDate];
                    
                    self.startDate = [NSDate new];
                    
                }
                
                self.dataModel = [TLBookListForSSModel mj_objectWithKeyValues:requestModel.data];
                
                self.unlockView.hidden = !self.dataModel.isShowDialog;
                
                if (self.dataModel.isShowDialog) {
                    self.unlockView.titleStr = self.dataModel.lastReadChapterName;
                }
                
                [self.cellTypeArr addObject:@(UIShortStoryCellTypeHeader)];
                
                self.dataModel.tl_cellHeight = 126 + [self calculateContentHeight:self.dataModel.desc];
                
                int scrollToIndex = 0;
                
                if (self.dataModel.thisChapter.count>0) {
                    int i = 0;
                    for (TLSSModel *model in self.dataModel.thisChapter) {
                        
                        model.tl_cellHeight = [self calculateContentHeight:model.content];
                        
                        [self.cellTypeArr addObject:@(UIShortStoryCellTypeContent)];
                        
                        if (model.chapterId.intValue == self.dataModel.lastReadChapterId.intValue) {
                            scrollToIndex = i;
                            NSLog(@"有历史记录 id:%d",model.chapterId.intValue);
                            NSLog(@"scrollToIndex id:%d",scrollToIndex);
                            self.curChaptertId = self.dataModel.lastReadChapterId;
                        }
                        i++;
                    }
                    
                }
                
                if (self.dataModel.isPayChapter.intValue != 0) {
                    [self.cellTypeArr addObject:@(UIShortStoryCellTypeVip)];
                }
                
                [self.cellTypeArr addObject:@(UIShortStoryCellTypeComment)];
                
                if (self.dataModel.osWorksNextVO.worksId.intValue != 0) {
                    
                    [self.cellTypeArr addObject:@(UIShortStoryCellTypeLock)];
                    
                    [self.cellTypeArr addObject:@(UIShortStoryCellTypeNextHeader)];
                }
                
                _navTitleLab.text = self.dataModel.worksName;
                
//                _navigationView.title = self.dataModel.worksName;
                
                [self.tableView reloadData];
                
                if (self.dataModel.osWorksNextVO && self.dataModel.osWorksNextVO.worksId.intValue != 0) {
                    [self.bottomView canNextStatusWithCanUse:YES];
                }else{
                    [self.bottomView canNextStatusWithCanUse:NO];
                }
                
                if (self.historyMArray.count>0) {
                    [self.bottomView canPrevStatusWithCanUse:YES];
                }else{
                    [self.bottomView canPrevStatusWithCanUse:NO];
                }
                
                if (self.dataModel.collectStatus) {
                    [self.bottomView collectStatusWithCollect:YES];
                }else{
                    [self.bottomView collectStatusWithCollect:NO];
                }
                
                if (scrollToIndex != 0 && !self.isNoScroll) {
//                    [NSIndexPath indexPathForRow:scrollToIndex+1 inSection:0]
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        
                        [self.tableView scrollToRow:scrollToIndex+1 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:NO];
                        
                    });
                }else{
                    
                    [self.tableView scrollToRow:0 inSection:0 atScrollPosition:UITableViewScrollPositionTop animated:NO];
                    
                    self.isNoScroll = NO;
                }
                
                if (success) {
                    
                    success();
                    
                }
                
            });
            
        }else{
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:requestModel.msg];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [TL_TopAlertManager showAlertWithError:error defaultText:WXLocalizedString(@"书籍获取失败")];
        
        [loadinView removeFromSuperview];
    }];
}
- (void)networkWithWorksId:(NSNumber *)worksId success:(MKVoidBlock)success{
    [self networkWithWorksId:worksId success:success delay:0];
}
- (void)buyBookAction{
    
    UIView *loadinView = [TL_TopAlertManager showLoading:self.view];
    MJWeakSelf
    
    [APIManager sendPostRequest:[APIURLManager getUsersBuyWorks] parameters:@{@"worksId":self.dataModel.worksId} model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        [loadinView removeFromSuperview];
        if (success) {
            
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"购买成功")];
            [self networkWithWorksId:self.dataModel.worksId success:nil];
            
        }else{
            
            TLAlterView *alterView = [TLAlterView createView];
            [alterView showActionWithTitle:@"Sorry, your balance is insufficient. Please top up your balance." andLeftBtnTitle:@"Back" andRightBtnTitle:@"Top up"];
            
            alterView.rightBtnBlock = ^{
                //跳转充值界面
                weakSelf.isSendRead = NO;
                TLRechargeCoinsViewController *vc = [TLRechargeCoinsViewController new];
                [weakSelf.navigationController pushViewController:vc animated:YES];
            };
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        NSLog(@"");
        
        [loadinView removeFromSuperview];
        
    }];
}
#pragma mark - table delegate - datasource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (self.cellTypeArr.count<=0 || indexPath.row>=self.cellTypeArr.count) {
        return [[UITableViewCell alloc] init];
    }
    
    NSNumber *cellType = self.cellTypeArr[indexPath.row];
    
    if (cellType.intValue == UIShortStoryCellTypeHeader) {
        TLShortStoryHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLShortStoryHeadTableViewCell"];
        cell.dataModel = self.dataModel;
        MJWeakSelf
        cell.collectBlock = ^(NSNumber *num) {
            
            [weakSelf collectionWorksWithId:num];
            
        };
        
        return cell;
    }else if (cellType.intValue == UIShortStoryCellTypeContent){
        TLShortStoryContentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLShortStoryContentTableViewCell"];

        if ((indexPath.row-1)<self.dataModel.thisChapter.count) {
            cell.dataModel = self.dataModel.thisChapter[indexPath.row-1];
        }
        cell.reloadBlock = ^{
            [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
        };
        return cell;
    }else if (cellType.intValue == UIShortStoryCellTypeVip){
        //展示vip界面
        TLShortStoryLockTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLShortStoryLockTableViewCell"];
        
        [cell.contentView setBackgroundColor:[UIColor colorWithHexString:@"F6F6F6"]];
        
        cell.dataModel = self.dataModel;
        MJWeakSelf
        cell.vipBlock = ^{
            weakSelf.isNoScroll = NO;
            weakSelf.isSendRead = NO;
            TLRechargeViewController *vc = [[TLRechargeViewController alloc] init];
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        cell.coinsBlock = ^{
            
            [self buyBookAction];
            
        };
        [cell refreshUI];
        
        return cell;
    }else if (cellType.intValue == UIShortStoryCellTypeComment){
        //展示评论 TLShortStoryCommentTableViewCell
        TLShortStoryCommentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLShortStoryCommentTableViewCell"];
        cell.dataModel = self.dataModel;
        MJWeakSelf
        cell.collectBlock = ^{
            [weakSelf collectionWorksWithId:weakSelf.dataModel.worksId];
        };
        cell.commentBlock = ^{
            weakSelf.isSendRead = NO;
            TL_CommentsViewController *vc = [[TL_CommentsViewController alloc] init];
            vc.production_id = weakSelf.dataModel.worksId.intValue;
            vc.commentsSuccessBlock = ^(TL_CommentsDetailModel *commentModel) {
                
            };
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        cell.viewAllBlock = ^{
            weakSelf.isSendRead = NO;
            TL_CommentsViewController *vc = [[TL_CommentsViewController alloc] init];
            vc.production_id = weakSelf.dataModel.worksId.intValue;
            vc.commentsSuccessBlock = ^(TL_CommentsDetailModel *commentModel) {
                
            };
            [weakSelf.navigationController pushViewController:vc animated:YES];
        };
        
        return cell;
    }else if (cellType.intValue == UIShortStoryCellTypeLock){
        
        TLShortStoryScrollTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLShortStoryScrollTableViewCell"];
        [cell refreshUI];
        
        return cell;
    }else if (cellType.intValue == UIShortStoryCellTypeNextHeader){
        
        TLShortStoryHeadTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TLShortStoryHeadTableViewCell"];
        
        cell.nextModel = self.dataModel.osWorksNextVO;
        
        return cell;
    }else{
        return [[UITableViewCell alloc] init];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    if (self.cellTypeArr.count<=0 || indexPath.row>=self.cellTypeArr.count) {
        return 0;
    }
    
    NSNumber *cellType = self.cellTypeArr[indexPath.row];
    CGFloat height = 0;
    switch (cellType.intValue) {
        case UIShortStoryCellTypeHeader:
            height = self.dataModel.tl_cellHeight;
            break;
        case UIShortStoryCellTypeNextHeader:
            height = 364;
            break;
        case UIShortStoryCellTypeContent:
        {
            if ((indexPath.row-1)<self.dataModel.thisChapter.count) {
                TLSSModel *model = self.dataModel.thisChapter[indexPath.row-1];
                return model.tl_cellHeight;
            }else{
                return 0;
            }
        }
            break;
        case UIShortStoryCellTypeVip:
        {
            height = 206;
        }
            break;
        case UIShortStoryCellTypeComment:
        {
            if ([self.dataModel.shortCommentVO.content isEqualToString:@""]) {
                height = 65;
            }else{
                height = 180;
            }
        }
            break;
        case UIShortStoryCellTypeLock:
        {
            height = 50;
        }
            break;
            
        default:
            break;
    }
    return height;
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.cellTypeArr.count;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self updateShowViewWithIsFull:!_isFullScreen];
    
}
- (UITableView *)tableView{
    if (!_tableView) {
        UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,MK_SCREEN_SAVE_BOTTOM_HEIGHT)];
        footView.backgroundColor = UIColor.clearColor;
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [MKReaderCfg shared].bgColor;
        _tableView.tableFooterView = footView;
        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = YES;
        if (@available(iOS 15.0, *)) {
            self.tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.frame = CGRectMake(0, CGRectGetMaxY(self.navView.frame), kScreenWidth, kScreenHeight+300);
        [_tableView registerNib:[UINib nibWithNibName:@"TLShortStoryHeadTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLShortStoryHeadTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"TLShortStoryContentTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLShortStoryContentTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"TLShortStoryLockTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLShortStoryLockTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"TLShortStoryScrollTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLShortStoryScrollTableViewCell"];
        [_tableView registerNib:[UINib nibWithNibName:@"TLShortStoryCommentTableViewCell" bundle:nil] forCellReuseIdentifier:@"TLShortStoryCommentTableViewCell"];
        
        // 设置下拉刷新
        MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadLastData)];
        
        // 设置刷新控件的标题
        [header setTitle:@"下拉刷新" forState:MJRefreshStateIdle];
        [header setTitle:@"松开刷新" forState:MJRefreshStatePulling];
        [header setTitle:@"正在刷新..." forState:MJRefreshStateRefreshing];
        
        // 获取箭头图标和状态标签
        UIImageView *arrowImageView = header.arrowView;
        UILabel *stateLabel = header.stateLabel;
        
        // 自定义布局：将箭头图标移动到文字正上方
        arrowImageView.translatesAutoresizingMaskIntoConstraints = NO;
        [header addSubview:arrowImageView];
        
        // 调整箭头和文字的布局
        [arrowImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(header);
            make.bottom.equalTo(stateLabel.mas_top).offset(-10); // 将箭头放在文字的正上方
            make.width.equalTo(@10);  // 控制箭头的大小
            make.height.equalTo(@20); // 控制箭头的大小
        }];
        header.lastUpdatedTimeLabel.hidden = YES;  // 隐藏时间标签（可选）
        // 设置下拉刷新头部
        _tableView.mj_header = header;
    }
    return _tableView;
}
- (void)loadLastData{
    
    [_tableView.mj_header endRefreshing];
}

// 在 UITableViewController 中实现滚动代理方法
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // 判断是否是 UITableView 的滚动
    [self updateShowViewWithIsFull:YES];
    if (scrollView == self.tableView) {
        [self checkChapter:scrollView];
        // 获取当前的偏移量
        CGFloat contentOffsetY = scrollView.contentOffset.y;
        
        CGFloat af = contentOffsetY/60;
        
        if (af>1) {
            af = 1;
        }else if(af<0){
            af = 0;
        }
        
        if ([MKReaderCfg shared].bgColorIndex.intValue == 0) {
            self.navTitleLab.textColor = [UIColor colorWithWhite:0 alpha:af];
        }else{
            self.navTitleLab.textColor = [UIColor colorWithWhite:1 alpha:af];
        }
        
        // 获取表格的内容高度和可见区域的高度
        CGFloat contentHeight = scrollView.contentSize.height;
        CGFloat tableViewHeight = scrollView.frame.size.height;
        
        // 判断是否滑动到最底部
        if (contentOffsetY + tableViewHeight > contentHeight) {
            // 计算弹簧效果的偏移量（即超过内容的部分）
            CGFloat pullDistance = contentOffsetY + tableViewHeight - contentHeight;
            // 如果偏移量大于 50，输出"上拉加载"
            if (pullDistance > 50 && pullDistance < 100) {
                self.scrollStatus = 1;
                if (!self.isLoading) {
                    
                    [[NSNotificationCenter defaultCenter] postNotificationName:TLShortStoryScrollStatusNotification object:@"Swipe up for next story" userInfo:@{@"ShowType":@"1"}];
                }
            }
            // 如果偏移量大于 100，输出"松开加载"
            else if (pullDistance >= 100) {
                self.scrollStatus = 2;
                if (!self.isLoading) {
                    [[NSNotificationCenter defaultCenter] postNotificationName:TLShortStoryScrollStatusNotification object:@"Release to view" userInfo:@{@"ShowType":@"2"}];
                }
            }else if (pullDistance <= 40) {
                self.scrollStatus = 0;
                //                [[NSNotificationCenter defaultCenter] postNotificationName:TLShortStoryScrollStatusNotification object:@"" userInfo:@{@"ShowType":@"0"}];
            }
        }
    }
}
- (void)checkChapter:(UIScrollView *)scrollView{
    CGFloat currentOffsetY = scrollView.contentOffset.y;
          
          // 获取当前最接近屏幕中心的cell
          NSArray *visibleCells = [self.tableView visibleCells];
          TLShortStoryContentTableViewCell *centerCell = nil;
          CGFloat screenCenterY = CGRectGetHeight(self.tableView.frame) / 2 + currentOffsetY;
          CGFloat minDistance = CGFLOAT_MAX;
          
          for (UITableViewCell *cell in visibleCells) {
              if ([cell isKindOfClass:[TLShortStoryContentTableViewCell class]]) {
                  CGFloat cellCenterY = cell.center.y;
                  CGFloat distance = fabs(cellCenterY - screenCenterY);
                  
                  if (distance < minDistance) {
                      minDistance = distance;
                      centerCell = (TLShortStoryContentTableViewCell *)cell;
                  }
              }
          }
          
          if (centerCell) {
              NSIndexPath *indexPath = [self.tableView indexPathForCell:centerCell];
              if (indexPath && indexPath.row-1 < self.dataModel.thisChapter.count) {
                  TLSSModel *dataModel = self.dataModel.thisChapter[indexPath.row-1];
                  
                  // 检查这个cell是否已经滚动超过100点
                  CGRect cellRectInTableView = [self.tableView rectForRowAtIndexPath:indexPath];
                  CGRect cellRectInSuperview = [self.tableView convertRect:cellRectInTableView toView:self.tableView.superview];
                  
                  CGFloat visibleHeight = 0;
                  if (cellRectInSuperview.origin.y < 0) {
                      // cell顶部在屏幕上方
                      visibleHeight = cellRectInSuperview.size.height + cellRectInSuperview.origin.y;
                  } else if (CGRectGetMaxY(cellRectInSuperview) > CGRectGetHeight(self.tableView.frame)) {
                      // cell底部在屏幕下方
                      visibleHeight = CGRectGetHeight(self.tableView.frame) - cellRectInSuperview.origin.y;
                  } else {
                      // cell完全在屏幕内
                      visibleHeight = cellRectInSuperview.size.height;
                  }
                  
                  // 只有当cell可见部分超过100点时才更新
                  if (visibleHeight >= 100.0 && ![self.curChaptertId isEqualToNumber:dataModel.chapterId]) {
                      NSLog(@"Cell可见高度超过阈值 - Section: %ld, Row: %ld chapterId:%@ (可见高度: %.1f)",
                            (long)indexPath.section, (long)indexPath.row, dataModel.chapterId, visibleHeight);
                      self.curChaptertId = dataModel.chapterId;
                  }
              }
          }
          
}
// 监听用户松开手指时的滚动偏移
- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView
                     withVelocity:(CGPoint)velocity
              targetContentOffset:(inout CGPoint *)targetContentOffset {
    
    // 判断偏移量是否大于100
    if (self.scrollStatus == 2) {
        //        [self.tableView setContentOffset:CGPointMake(0, kScreenHeight) animated:YES ];
        NSLog(@"加载中");
        [[NSNotificationCenter defaultCenter] postNotificationName:TLShortStoryScrollStatusNotification object:@"Loading..." userInfo:@{@"ShowType":@"3"}];
        
        if (_isLoading) {
            return;
        }
        
        if (self.worksId) {
            [self.historyMArray addObject:[NSNumber numberWithString:self.worksId]];
        }
        
        self.isLoading = YES;
        [self networkWithWorksId:self.dataModel.osWorksNextVO.worksId success:^{
            
            [[NSNotificationCenter defaultCenter] postNotificationName:TLShortStoryScrollStatusNotification object:@"" userInfo:@{@"ShowType":@"0"}];
            self.isLoading = NO;
            self.scrollStatus = 0;
            self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.navView.frame), kScreenWidth, kScreenHeight);
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [self.tableView setContentOffset:CGPointMake(0, kScreenHeight+PUB_NAVBAR_HEIGHT) animated:YES];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.tableView setContentOffset:CGPointMake(0, - kStatusBarHeight) animated:NO];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        self.tableView.frame = CGRectMake(0, CGRectGetMaxY(self.navView.frame), kScreenWidth, kScreenHeight+300);
                    });
                });
            });
            
        } delay:1.5];
        
        
    }
}
// 高度计算方法
- (CGFloat)calculateContentHeight:(NSString *)Str {
    NSString *htmlString = Str; // 新增预处理
    if (htmlString.length == 0) return 0;
    
    UILabel *lab = [UILabel new];
    
//    [lab attributedStringWithHTMLText:htmlString fontSize:18 characterSpacing:0 lineSpacing:16 paragraphSpacing:18 alignment:NSTextAlignmentLeft];
    
    [lab attributedStringWithHTMLText:htmlString
                                         fontSize:[MKReaderCfg shared].fontSize.intValue
                                 characterSpacing:[MKReaderCfg shared].characterSpacingSize.intValue
                                      lineSpacing:[MKReaderCfg shared].lineSpacing.intValue
                                 paragraphSpacing:[MKReaderCfg shared].paragraphSpacing.intValue
                                        alignment:NSTextAlignmentLeft];
    
    
    // 1. 尝试从缓存获取富文本
//    NSAttributedString *attributedText = [TL_UtilsHelper attributedStringFromHTMLString:htmlString];
    
    NSAttributedString *attributedText = lab.attributedText;
    
    //    if (!attributedText) {
    //        // 2. 转换 HTML 字符串
    //        attributedText = [self attributedStringFromHTMLString:htmlString];
    //        [self.htmlCache setObject:attributedText forKey:htmlString];
    //    }
    
    // 3. 计算高度
    CGFloat fixedWidth = kScreenWidth - 22 * 2;
    CGRect textRect = [attributedText boundingRectWithSize:CGSizeMake(fixedWidth, CGFLOAT_MAX)
                                                   options:NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading
                                                   context:nil];
    CGFloat totalHeight = ceil(CGRectGetHeight(textRect)) + 8 + 26 + 11 + 30;
    
    lab = nil;
    
    return totalHeight;
}

- (void)collectionWorksWithId:(NSNumber *)number{
    
        if(!TL_UserInfoManager.isLogin){
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:WXLocalizedString(@"未登录")];
            return;
        }
    
    NSDictionary *param = @{
        @"worksId":number
    };
    
    NSString *url = [APIURLManager collectBook];
    
    if (self.dataModel.collectStatus) {
        url = [APIURLManager cancelCollectBook];
        param = @{
            @"worksIds":@[number]
        };
    }
    
    [APIManager sendPostRequest:url parameters:param model:nil success:^(BOOL success, id  _Nullable responseData, APIResponse * _Nonnull requestModel) {
        
        if (success) {
            
            self.dataModel.collectStatus = !self.dataModel.collectStatus;
            
            if (self.dataModel.collectStatus) {
                [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"收藏成功")];
                self.dataModel.collectNum = [NSNumber numberWithInt:self.dataModel.collectNum.intValue + 1];
                [self.bottomView collectStatusWithCollect:YES];
            }else{
                [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeSuccess alertTitle:WXLocalizedString(@"取消成功")];
                self.dataModel.collectNum = [NSNumber numberWithInt:self.dataModel.collectNum.intValue - 1];
                [self.bottomView collectStatusWithCollect:NO];
            }
            
            [self.tableView reloadData];
            
        }else{
            
            [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:WXLocalizedString(@"添加失败")];
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [TL_TopAlertManager showAlertWithType:TL_TopAlertTypeError alertTitle:WXLocalizedString(@"添加失败")];
    }];
    
}
#pragma mark - lazy load

- (MKReaderSettingView *)settingView{
    if (!_settingView) {
        _settingView = [MKReaderSettingView createView];
        _settingView.delegate = self;
        [_settingView statusForShortStory];
    }
    return _settingView;
}
- (MKReaderBottomView *)bottomView{
    if (!_bottomView) {
        _bottomView = [MKReaderBottomView createView];
        
        MJWeakSelf
        _bottomView.btnActionBlock = ^(NSInteger type) {
            
            switch (type) {

                case DJReaderBVButtonType_save:
                    //收藏
                {
                    [weakSelf collectionWorksWithId:weakSelf.dataModel.worksId];
                }
                    break;
                case DJReaderBVButtonType_comment:
                    //评论
                {
                    weakSelf.isSendRead = NO;
                    TL_CommentsViewController *vc = [[TL_CommentsViewController alloc] init];
                    vc.production_id = weakSelf.dataModel.worksId.intValue;
                    vc.commentsSuccessBlock = ^(TL_CommentsDetailModel *commentModel) {
                        
                    };
                    [weakSelf.navigationController pushViewController:vc animated:YES];
                }
                    break;
                case DJReaderBVButtonType_previous:
                    //上一章
                    weakSelf.worksId = [NSString stringWithFormat:@"%@",[weakSelf.historyMArray lastObject]];
                    
                    [weakSelf.historyMArray removeLastObject];
                    
                    [weakSelf networkWithWorksId:[NSNumber numberWithString:weakSelf.worksId] success:nil];
                    
                    break;
                case DJReaderBVButtonType_next:
                    //下一章
                    
                    weakSelf.worksId = [NSString stringWithFormat:@"%@",weakSelf.dataModel.osWorksNextVO.worksId];
                    
                    [weakSelf.historyMArray addObject:weakSelf.dataModel.worksId];
                    
                    [weakSelf networkWithWorksId:[NSNumber numberWithString:weakSelf.worksId] success:nil];
                    
                    break;

                case DJReaderBVButtonType_dayNight:
                    //夜间
                    [weakSelf setupReaderContentWithIsUpdateStyle:YES];
                    
                    
                    break;
                    
                default:
                    break;
            }
            
        };
    }
    return _bottomView;
}
//- (MKReaderNavigationView *)navigationView{
//    if (!_navigationView) {
//        _navigationView = [MKReaderNavigationView createView];
//        _navigationView.delegate = self;
//    }
//    return _navigationView;
//}

- (void)setupReaderContentWithIsUpdateStyle:(BOOL)isUpdateStyle{
    if (isUpdateStyle) {
        
//        [_bottomView refreshStyleUI];
        
        [self setNeedsStatusBarAppearanceUpdate];
        
    }
    [self resetUI:NO];
}
- (void)resetUI:(BOOL)isFirst{
    
//    [self.navigationView refreshStyleUI];
    
    CGFloat alphaF = !isFirst;
    
    if ([MKReaderCfg shared].bgColorIndex.intValue == 0) {
        [self.navView setBackgroundColor:[UIColor whiteColor]];
        self.navTitleLab.textColor = [UIColor colorWithWhite:0 alpha:alphaF];
        [_backBtn setImage:[UIImage imageNamed:@"tzxqy_fh"] forState:UIControlStateNormal];
    }else{
        [self.navView setBackgroundColor:[UIColor hex_191820]];
        self.navTitleLab.textColor = [UIColor colorWithWhite:1 alpha:alphaF];
        [_backBtn setImage:[UIImage imageNamed:@"ydy_fh"] forState:UIControlStateNormal];
    }
    
    [self.navView setBackgroundColor:[[MKReaderCfg shared] bgColor]];
    
//    [self.tableView setBackgroundColor:[[MKReaderCfg shared] bgColor]];
    
    [self.settingView refreshStyleUI];
    
    [self.tableView reloadData];
    
    [self.view setBackgroundColor:[[MKReaderCfg shared] bgColor]];
    
}

- (void)updateShowViewWithIsFull:(BOOL)isFull{
    
    if (isFull==self.isFullScreen) {
        return;
    }
    self.isFullScreen = isFull;
    
    
//    [_navigationView showViewWithShow:!isFull];
    [_bottomView showViewWithShow:!isFull];

    [self.settingView showViewWithShow:!isFull];
    
    if (!isFull) {
        
        CGRect frame = self.unlockView.frame;
        
        frame.origin.y = kScreenHeight - 88 - 13 - self.bottomView.height - self.settingView.height;
         
        [UIView animateWithDuration:0.3 animations:^{
            self.unlockView.frame = frame;
        }];
        
    }else{
        
        CGRect frame = self.unlockView.frame;
        
        frame.origin.y = kScreenHeight - 88 - 13 - MK_SCREEN_SAVE_BOTTOM_HEIGHT;
         
        [UIView animateWithDuration:0.3 animations:^{
            self.unlockView.frame = frame;
        }];
        
    }
    
    
    [self.view bringSubviewToFront:self.bottomView];
    
    [self setNeedsStatusBarAppearanceUpdate];
    
}

- (void)likeActionWithButton:(UIButton * _Nonnull)button {
    NSLog(@"likeActionWithButton");
}

- (void)moreBtnActionWithIsShow:(BOOL)isShow {
    NSLog(@"moreBtnActionWithIsShow");
}

- (void)reportAction {
    NSLog(@"reportAction");
}

- (void)shareAction {
    NSLog(@"shareAction");
}

- (void)settingBgColorWithSettingView:(MKReaderSettingView * _Nonnull)settingView {
    NSLog(@"settingBgColorWithSettingView");
}

- (void)settingFontSizeWithSettingView:(MKReaderSettingView * _Nonnull)settingView {
    
    if (self.dataModel.thisChapter.count>0) {
        
        for (TLSSModel *model in self.dataModel.thisChapter) {
            
            model.tl_cellHeight = [self calculateContentHeight:model.content];
            
        }
        
    }
    
    self.dataModel.tl_cellHeight = 126 + [self calculateContentHeight:self.dataModel.desc];
    
    [self.tableView reloadData];
    
}
- (void)settingPagingEffectWithSettingView:(MKReaderSettingView * _Nonnull)settingView {
    NSLog(@"settingPagingEffectWithSettingView");
}
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleDefault;
}
@end
